package com.lhg.tcp;


import com.lhg.serve.*;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class ServeThread extends Thread{
    private Socket socket;

    public ServeThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        // 获取请求输入流
        OutputStream outputStream = null;
        InputStream inputStream = null;
        try {

            inputStream = socket.getInputStream();

            HttpRequest request = HttpRequestHandler.getRequest(inputStream);

            String path = Constant.ROOT_DIR+request.getUri();


            System.out.println(request);
            outputStream = socket.getOutputStream();
            HttpResponse response = new HttpResponse();
            String body = IOUtils.getContext(path);
            if (body!=null){
                response.setHeader("Content-Type","text/html");
                response.setHeader("Content-Length",body.getBytes().length+"");
                response.setBody(body);

                HttpResponseHandler.write(outputStream,response);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                inputStream.close();
                outputStream.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
